package com.scalar.chiptrack.operations.dataentry.inventoryReceive.actioncommands;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.operations.dataentry.dao.DataEntryDAO;
import com.scalar.chiptrack.operations.dataentry.LotDetails;
import com.scalar.chiptrack.operations.dataentry.InTransitLots;
import com.scalar.chiptrack.operations.dataentry.inventoryReceive.forms.InventoryReceiveForm;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.sales.SubTotal;
import com.scalar.chiptrack.commons.SessionKeys;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * Created by IntelliJ IDEA.
 * User: ChandraSekhar
 * Date: Fed 06, 2008
 * Time: 12:28:08 PM
 */
public class InventoryReceiveSaveCommand extends ActionCommand
{
    private static final String ACTION_NAME = "/inventoryReceive.do";

    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception
    {

       InventoryReceiveForm invReceiveForm = (InventoryReceiveForm) form;

        HashMap errors = new HashMap();
        HashMap info = new HashMap();
        String action = request.getParameter("action");

        request.setAttribute(INFO_MESSAGES, info);
        request.setAttribute(ERROR_MESSAGES, errors);


        HttpSession mSession = request.getSession();
        User user = (User) mSession.getAttribute(SessionKeys.USER_KEY);

        if (user == null)
        {
            mSession.setAttribute(SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME);
            return (mapping.findForward("login"));
        }
        else
        {
            if (user.isActionAllowed(Functionality.DATA_ENTRY, User.USER_ACTION_MODIFY))
            {
                request.setAttribute("showMessage", "FALSE");
            }
            else
            {
                request.setAttribute("showMessage", "TRUE");
            }
        }

        LotDetails  lotDetails = new LotDetails();
        InTransitLots invReciveLots = null;
        DBTransaction dbTranasaction    = null;

        if ( "save".equalsIgnoreCase( action ) )
        {
            LinkedHashMap hash = new LinkedHashMap();
            ArrayList arrList  = new ArrayList();
            
           //for Confirm Screen
            for (int i = 0; i < invReceiveForm.getTransitLotsList().size(); i++)
            {
                invReciveLots = (InTransitLots) invReceiveForm.getTransitLotsList().get(i);

                if ( invReciveLots.isChecked() )
                {
                        if ("0".equalsIgnoreCase( invReciveLots.getDateCode() ))
                        {
                             invReciveLots.setDateCode( invReciveLots.getDateCode1() );
                        }
                        else if ("-1".equals(invReciveLots.getDateCode() ) || LOCATION_TYPE_ASSEMBLY.equalsIgnoreCase(invReceiveForm.getProcessType() ) )
                        {
                             invReciveLots.setDateCode(null);
                        }
                       
                        String partNumber = invReciveLots.getPartNumber();
                        if ( !( hash.containsKey ( partNumber ) ) )
                        {
                            hash.put ( partNumber, new ArrayList() );
                        }
                        arrList = ( ArrayList ) hash.get ( partNumber );

                        arrList.add ( invReciveLots );
                }
            }

            Iterator iterator = hash.keySet().iterator();
            LinkedHashMap hashMap = new LinkedHashMap ();

            while ( iterator.hasNext () )
            {
                String str = ( String ) iterator.next ();
                ArrayList newarrList = ( ArrayList )hash.get ( str );
                SubTotal subTotal = new SubTotal();
                int subTotalQty = 0;

                for ( int j = 0; j < newarrList.size (); j++ )
                {
                    subTotalQty = subTotalQty + Integer.parseInt(( (InTransitLots)newarrList.get( j ) ).getShipQty() );
                }
                subTotal.setSubTotalQty( Integer.toString ( subTotalQty )  );

                hashMap.put ( newarrList, subTotal );
            }
            request.setAttribute("subTotalMap", hashMap );
            request.setAttribute("action", action);

            saveToken( request );

            return mapping.findForward( "inventoryReceiveConfirm" );

        }
        else
        {   try
            {
                if ( isTokenValid( request ) )
                {
                    DataEntryDAO.saveInventoryReceiveInfo( dbTranasaction, invReceiveForm.getTransitLotsList(), user.getUserName() );
                    resetToken( request );
                    info.put("Lots received to "+invReceiveForm.getProcessType() + " Successlly", null);
                }
                else
                {
                    errors.put("Invalid Request" , null );
                }
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( "Could not save ineventory receive lots", null );
            }

            invReceiveForm.setProcessType("0");
            invReceiveForm.setProcessStepId(0);
            invReceiveForm.setLocationId(0);
            invReceiveForm.setLotId(0);
            invReceiveForm.setTransitLotsList( null );

            request.setAttribute("processTypeList", lotDetails.getInventoryReceiveProcessList());
            request.setAttribute("action", action);
        }
        return mapping.findForward( "inventoryReceive" );
    }
}
